package com.liip.platform.config.jwt;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.liip.platform.entity.User;

import lombok.extern.slf4j.Slf4j;


import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * @description: Jwt工具类，生成JWT和认证
 * @author: Java碎碎念
 */
@Slf4j
@Component
public class JwtConfig {
	
    /**
     * 	密钥
     */
	@Value("${config.jwt.secret}")
	private String secret;

    /**
     * 	过期时间
     **/
	@Value("${config.jwt.expire}")
	private long expire;//单位为秒
	
	@Value("${config.jwt.header}")
	private String header;
    /**
     * 	生成用户token,设置token超时时间
     */
    public String createToken(User user) {
        //过期时间
    	Date nowDate = new Date();
        Date expireDate = new Date(nowDate.getTime() + expire * 1000);//过期时间
        
        Map<String, Object> map = new HashMap<>();
        map.put("alg", "HS256");
        map.put("typ", "JWT");
        String token = JWT.create()
                .withHeader(map)// 添加头部
                //可以将基本信息放到claims中
                .withClaim("id", user.getId())//userId
                .withClaim("loginName", user.getLoginName())//userName
                .withClaim("lealName", user.getRealName())//name
                .withExpiresAt(expireDate) //超时设置,设置过期的日期
                .withIssuedAt(new Date()) //签发时间
                .sign(Algorithm.HMAC256(secret)); //SECRET加密
        return token;
    }
    /**
     * 验证token是否过期生效
     * @param expireTime
     * @return
     */
    public boolean isTokenExpired(Date expireTime) {
    	return expireTime.before(new Date());
	}
    /**
     * 	校验token并解析token
     */
    public Map<String, Claim> verifyToken(String token) {
        DecodedJWT jwt = null;
        try {
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(secret)).build();
            jwt = verifier.verify(token);
           //判断是否过期
           if(isTokenExpired(jwt.getIssuedAt())) {
            	return null;
           }
        } catch (Exception e) {
            //log.error(e.getMessage());
            //log.error("token解码异常");
            //解码异常则抛出异常
            return null;
        }
        return jwt.getClaims();
    }

    
    // --------------------- getter & setter ---------------------
 
    public String getSecret() {
        return secret;
    }
    public void setSecret(String secret) {
        this.secret = secret;
    }
    public long getExpire() {
        return expire;
    }
    public void setExpire(long expire) {
        this.expire = expire;
    }
    public String getHeader() {
        return header;
    }
    public void setHeader(String header) {
        this.header = header;
    }
}